import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Cascader, DatePicker, Input, Select, Button, Table, Modal, Pagination, Drawer, message } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import { DEFAULT_PAGE_SIZE, DEFAULT_VALID_STATE } from '@/constants';
import styles from './index.less';

import Edit from './edit';
import History from './history';
import Message from './message';
import Process from './process';
import Unit from '@/pages/Organization/Unit';

const { confirm } = Modal;
const { Content } = Layout;
const { RangePicker } = DatePicker;
const { Option } = Select;

const CONST_MODE_SELECT = 'select';
const CONST_MODE_LIST = 'list';

const CONDITIONS = [
  { label: '事发时间', field: 'query.eventTheTime', type: 'dateRange' },
  { label: '接报时间', field: 'query.eventCriminal', type: 'dateRange' },
  {
    label: '发生区域', field: 'query.areaId', type: 'cascader', modularField: 'areas', placeholder: '请选择发生区域', fieldNames: { label: 'areaName', value: 'id', children: 'children' },
    loadData: (that, selectedOptions) => {
      const { dispatch } = that.props;
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;

      dispatch({
        type: `${that.modularName}/queryAreaTree`,
        payload: {
          areaPid: `${targetOption.id}`,
          isLeaf: targetOption.areaType === '3',
          callback: (data) => {
            targetOption.loading = false;
            targetOption.children = data;
          }
        }
      })
    }
  },
  { label: '来源', field: 'query.eventSource', type: 'input', placeholder: '请选择输入来源' },
  { label: '事件简述', field: 'query.eventBrief', type: 'input', placeholder: '请选择事件简述' },
  { label: '推送单位', field: 'query.unitId', type: 'select', modularField: 'units', placeholder: '请选择推送单位' }
];

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'emergency';
    const { global, mode } = props;
    const { currentUnit = {} } = global;
    this.state = {
      query: {
        orderBy: 'eventCreateTime',
        eventSubordinateUnit: `${currentUnit.id}`
      },
      selectedUnits: [],
      mode: mode || CONST_MODE_LIST
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryAreaTree`,
      payload: {
        areaPid: '1',
        isLeaf: false
      }
    });
    dispatch({
      type: `unit/queryData`,
      payload: {
        state: DEFAULT_VALID_STATE,
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          dispatch({
            type: `${this.modularName}/changeState`,
            payload: { units: data }
          });
        }
      }
    });
    this.queryData(1, this.state.mode === CONST_MODE_LIST ? DEFAULT_PAGE_SIZE : DEFAULT_PAGE_SIZE / 2);
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` })
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增突发事件', editData: {} }
    });
  }

  pushBtnClick = (record, e) => {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '选择部门', editData: record }
    });
  }

  editBtnClick = (record, e) => {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑突发事件', editData: record }
    });
  }

  stopBtnClick = (record, e) => {
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    confirm({
      title: '是否确认删除该数据?',
      onOk: () => {
        const { query = {} } = this.state;
        const { dispatch, modular } = this.props;
        const { current, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            ids: Array.isArray(record) ? record.map(item => item.id) : [record.id],
            ...query,
            current,
            pageSize
          }
        });
      },
      onCancel() { },
    });
  }

  toggleTopBtnClick = (record, state, e) => {
    const { query = {} } = this.state;
    const { dispatch, modular } = this.props;
    const { current, pageSize } = modular;

    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    dispatch({
      type: `${this.modularName}/toggleTop`,
      payload: {
        id: record.id,
        state,
        ...query,
        current,
        pageSize
      }
    });
  }

  searchBtnClick = () => {
    const { form, global, modular } = this.props;
    const { currentUnit = {} } = global;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    form.validateFields((err, values) => {
      const { query = {} } = values;
      let { areaId, eventTheTime, eventCriminal, unitId, ...extra } = query;
      let eventStartTheTime, eventEndTheTime, eventStartCriminal, eventEndCriminal;

      if (eventTheTime && eventTheTime[0]) {
        eventStartTheTime = eventTheTime[0].format('YYYY-MM-DD HH:mm:ss');
      }
      if (eventTheTime && eventTheTime[1]) {
        eventEndTheTime = eventTheTime[1].format('YYYY-MM-DD HH:mm:ss');
      }
      if (eventCriminal && eventCriminal[0]) {
        eventStartCriminal = eventCriminal[0].format('YYYY-MM-DD HH:mm:ss');
      }
      if (eventCriminal && eventCriminal[1]) {
        eventEndCriminal = eventCriminal[1].format('YYYY-MM-DD HH:mm:ss');
      }
      if (areaId && areaId.length > 0) {
        areaId = `#${areaId[areaId.length - 1]}#`;
      }

      this.setState({
        query: {
          ...this.state.query,
          areaId: Array.isArray(areaId) && areaId.length === 0 ? undefined : areaId,
          eventStartTheTime, eventEndTheTime, eventStartCriminal, eventEndCriminal,
          unitId: Array.isArray(unitId) && unitId.length === 0 ? undefined : unitId,
          ...extra
        }
      }, () => {
        this.queryData(1, pageSize);
      });
    });
  }

  clearBtnClick = () => {
    const { form, global, modular } = this.props;
    const { currentUnit = {} } = global;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    form.resetFields()
    this.setState({
      query: {
        orderBy: 'eventCreateTime',
        eventSubordinateUnit: `${currentUnit.id}`
      }
    }, () => {
      this.queryData(1, pageSize);
    })
  }

  queryData = (current, pageSize) => {
    const { query = {} } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize
      }
    });
  }

  onChange = (current, pageSize) => {
    this.queryData(current, pageSize);
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize)
  }

  onOk = () => {
    const { query = {} } = this.state;
    const { dispatch, form, global, modular } = this.props;
    const { currentUnit = {} } = global;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { query: nouse, ...data } = values;
        let { eventType, areaId, eventTheTime, eventCriminal, eventInjured, eventDeath, ...extra } = data;

        if (Array.isArray(eventType) && eventType.length > 0) {
          eventType = eventType.join('/');
        }
        if (Array.isArray(areaId) && areaId.length > 0) {
          areaId = areaId.map(item => `#${item}#`).join(',');
        }
        if (eventTheTime) {
          eventTheTime = eventTheTime.format('YYYY-MM-DD HH:mm:ss');
        }
        if (eventCriminal) {
          eventCriminal = eventCriminal.format('YYYY-MM-DD HH:mm:ss');
        }
        if (eventInjured) {
          eventInjured = `${eventInjured}`;
        }
        if (eventDeath) {
          eventDeath = `${eventDeath}`;
        }

        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            data: {
              id: editData.id,
              ...editData,
              ...extra,
              eventType, areaId, eventTheTime, eventCriminal, eventInjured, eventDeath,
              eventSubordinateUnit: `${currentUnit.id}`
            },
            ...query,
            current,
            pageSize
          }
        });
      }
    });
  }

  onPush = () => {
    const { selectedRows = [], selectedUnits = [] } = this.state;
    const { dispatch, global, modular } = this.props;
    const { currentUnit = {} } = global
    const { editData = {} } = modular;

    if (!selectedUnits || selectedUnits.length === 0) {
      message.error('请选择要推送的单位', 1);
      return;
    }
    if (!(!_.isEmpty(editData) || selectedRows && selectedRows.length > 0)) {
      message.error('请选择要推送的数据', 1);
      return;
    }

    let list = [];
    selectedUnits.forEach(unit => {
      if (unit.id !== currentUnit.id) {
        const data = selectedRows.map(row => {
          return {
            eventId: row.id,
            pushTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            unit_id: {
              id: unit.id
            },
            pushUnitId: currentUnit.id
          }
        });

        list = [...list, ...data];
      }
    });

    if (!_.isEmpty(editData)) {
      list = [
        ...list,
        ...selectedUnits.map(unit => {
          if (unit.id !== currentUnit.id) {
            return {
              eventId: editData.id,
              pushTime: moment().format('YYYY-MM-DD HH:mm:ss'),
              unit_id: {
                id: unit.id
              },
              pushUnitId: currentUnit.id
            }
          }
        })
      ];
    }

    dispatch({
      type: `${this.modularName}/saveOrUpdateEventPush`,
      payload: {
        list: list.filter(item => item),
        callback: () => {
          this.setState({ selectedUnits: [] });
          dispatch({ type: `${this.modularName}/changeState`, payload: { visible: false, editData: {} } });
        }
      }
    });
  }

  render() {
    const { selectedUnits, selectedRows = [], mode } = this.state;
    const { dispatch, loading, form, global, modular } = this.props;
    const { getFieldDecorator } = form;
    const { currentUnit = {} } = global
    const { data = [], current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, rowKey, drawerVisible, visible, editData = {} } = modular;

    const columns = [
      {
        title: '事件标题',
        dataIndex: 'eventTitle',
        ellipsis: true,
        width: 320,
        fixed: 'left',
        render: (text, record) => {
          return <div style={{ width: 280, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }} title={text}>{text}</div>
        }
      },
      {
        title: '事件简述',
        dataIndex: 'eventBrief',
        ellipsis: true,
        width: 320,
      },
      {
        title: '发生区域',
        dataIndex: 'areaList',
        ellipsis: true,
        width: 320,
        render: (text, record) => {
          if (Array.isArray(text) && text.length > 0) {
            return text.map(item => item.areaName).join('-')
          }

          return '';
        }
      },
      {
        title: '事发地址',
        dataIndex: 'eventAddress',
        ellipsis: true,
        width: 320,
      },
      {
        title: '来源',
        dataIndex: 'eventSource',
        ellipsis: true,
        width: 200,
      },
      {
        title: '事发时间',
        dataIndex: 'eventTheTime',
        ellipsis: true,
        width: 200,
      },
      {
        title: '接报时间',
        dataIndex: 'eventCriminal',
        ellipsis: true,
        width: 200,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 300,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div>
              <div className={styles.common_span_group} style={{ marginBottom: 8 }}>
                <span onClick={(e) => { e.stopPropagation(); dispatch({ type: `${this.modularName}/changeState`, payload: { drawerVisible: '流程记录', editData: record } }) }}>流程记录{`(${record.processCount})`}</span>
                <span onClick={(e) => { e.stopPropagation(); dispatch({ type: `${this.modularName}/changeState`, payload: { drawerVisible: '信息送报', editData: record } }) }}>短信编报</span>
                {record.eventIsTop === 1 ?
                  <span style={{ color: 'grey' }} onClick={this.toggleTopBtnClick.bind(this, record, '0')}>取消置顶</span> :
                  <span style={{ color: '#ff4d4f' }} onClick={this.toggleTopBtnClick.bind(this, record, '1')}>置顶</span>
                }
              </div>
              <div className={styles.common_span_group}>
                <span onClick={this.pushBtnClick.bind(this, record)}>推送</span>
                <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
                <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>删除</span>
              </div>
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper} style={{ ...this.props.style }}>
        {mode !== CONST_MODE_SELECT &&
          <div div className={styles.title}>
            当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnit.unit_name}</span>
          </div>
        }
        <div className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')} style={mode === CONST_MODE_LIST ? {} : { marginBottom: 0 }}>
          {(mode === CONST_MODE_LIST ? CONDITIONS : CONDITIONS.slice(0, 2)).map(item => {
            if (item.type === 'dateRange') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(item.field, {
                    })(
                      <RangePicker style={{ width: 300 }} />
                    )}
                  </div>
                </div>
              );
            } else if (item.type === 'cascader') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(item.field, {
                    })(
                      <Cascader
                        changeOnSelect
                        fieldNames={item.fieldNames}
                        options={modular[item.modularField]}
                        placeholder={item.placeholder}
                        loadData={(selectedOptions) => item.loadData(this, selectedOptions)}
                        style={{ width: 300 }}
                      />
                    )}
                  </div>
                </div>
              );
            } else if (item.type === 'input') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(item.field, {
                    })(
                      <Input placeholder={item.placeholder} style={{ width: 300 }} />
                    )}
                  </div>
                </div>
              );
            } else if (item.type === 'select') {
              return (
                <div key={item.field} className={styles.item_wrapper}>
                  <div>{item.label}</div>
                  <div>
                    {getFieldDecorator(item.field, {
                    })(
                      <Select
                        allowClear={true}
                        mode='multiple'
                        placeholder={item.placeholder}
                        style={{ width: 300 }}
                        filterOption={(inputValue, option) => {
                          return option && option.props && option.props.children && option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                        }}
                      >
                        {modular[item.modularField] && modular[item.modularField].filter(item => item.id !== currentUnit.id).map(item => {
                          return <Option key={item.id} value={item.id}>{item.unit_name}</Option>
                        })}
                      </Select>
                    )}
                  </div>
                </div>
              );
            }
          })}
          <div className={styles.item_wrapper}>
            <Button icon='redo' style={{ marginRight: 16, minWidth: 90, marginBottom: 16 }} onClick={this.clearBtnClick}>重置</Button>
            <Button type='primary' icon='search' style={{ minWidth: 90, marginBottom: 16 }} onClick={this.searchBtnClick}>查询</Button>
          </div>
        </div>
        <Content className={[styles.conditions_wrapper, mode === CONST_MODE_SELECT ? styles.conditions_no_border_wrapper : null].join(' ')} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            {mode !== CONST_MODE_SELECT &&
              <div>
                <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16, marginBottom: 16 }} onClick={this.appendBtnClick}>新增</Button>
                <Button icon='delete' type='danger' style={{ marginRight: 16, marginBottom: 16 }} onClick={selectedRows && selectedRows.length > 0 ? this.stopBtnClick.bind(this, selectedRows) : undefined}>批量停用{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
                <Button icon='cloud-upload' className={styles.common_btn_type_orange} style={{ marginRight: 16, marginBottom: 16 }} onClick={selectedRows && selectedRows.length > 0 ? this.pushBtnClick.bind(this, {}) : undefined}>批量推送{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
                <Button icon='clock-circle' className={styles.common_btn_type_blue} style={{ marginRight: 16, marginBottom: 16 }} onClick={() => dispatch({ type: `${this.modularName}/changeState`, payload: { drawerVisible: '推送历史' } })}>推送历史</Button>
              </div>
            }
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={mode === CONST_MODE_LIST ? columns : columns.slice(0, columns.length - 1)}
                dataSource={data}
                loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                pagination={false}
                rowKey={rowKey}
                rowClassName={(record) => {
                  return record.eventIsTop === 1 ? styles.top_tr : null
                }}
                rowSelection={
                  mode === CONST_MODE_LIST ?
                    {
                      onChange: (selectedRowKeys, selectedEvents) => {
                        this.setState({ selectedRows: [...selectedRows.filter(item => selectedRowKeys.includes(item.id) && !selectedEvents.map(row => row.id).includes(item.id)), ...selectedEvents] })
                      }
                    } :
                    { ...this.props.rowSelection }
                }
                scroll={{ x: true }}
                onRow={record => {
                  return {
                    onClick: event => {
                      dispatch({
                        type: `${this.modularName}/changeState`,
                        payload: { visible: '查看突发事件', editData: record }
                      });
                    }
                  }
                }}
              />
            </Content>
            <div style={{ margin: '16px 0' }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                showQuickJumper
                showSizeChanger
                showTotal={(total, range) => `共有 ${total} 条数据`}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          </Layout>
        </Content>
        <Drawer
          destroyOnClose
          title={drawerVisible}
          placement='right'
          visible={!!drawerVisible}
          width={840}
          onClose={() => dispatch({ type: `${this.modularName}/changeState`, payload: { drawerVisible: false, editData: {} } })}
        >
          {drawerVisible === '信息送报' ?
            <Message
              dispatch={dispatch}
              form={form}
              modularName={this.modularName}
              currentUnit={currentUnit}
              event={editData}
            /> :
            drawerVisible === '流程记录' ?
              <Process
                dispatch={dispatch}
                form={form}
                modularName={this.modularName}
                currentUnit={currentUnit}
                event={editData}
              /> :
              drawerVisible === '推送历史' ?
                <History
                  dispatch={dispatch}
                  form={form}
                  modularName={this.modularName}
                  currentUnit={currentUnit}
                />
                : null
          }
        </Drawer>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={visible === '选择部门' ? 1115 : 560}
          okButtonProps={visible === '查看突发事件' ? { style: { display: 'none' } } : { loading: !!loading.effects[`${this.modularName}/saveOrUpdateData`] || !!loading.effects[`${this.modularName}/saveOrUpdateEventPush`] }}
          cancelButtonProps={visible === '查看突发事件' ? { style: { display: 'none' } } : { loading: !!loading.effects[`${this.modularName}/saveOrUpdateData`] || !!loading.effects[`${this.modularName}/saveOrUpdateEventPush`] }}
          onOk={visible === '选择部门' ? this.onPush : this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            });
            this.setState({ selectedUnits: [] });
          }}
        >
          {visible === '选择部门' ?
            <Unit
              mode='select'
              style={{ backgroundColor: '#fff' }}
              rowSelection={{
                onChange: (selectedRowKeys, selectedRows) => {
                  this.setState({ selectedUnits: [...selectedUnits.filter(item => selectedRowKeys.includes(item.id) && !selectedRows.map(row => row.id).includes(item.id)), ...selectedRows] })
                }
              }}
            /> :
            <Edit
              dispatch={dispatch}
              form={form}
              modularName={this.modularName}
              areas={modular.areas}
              data={editData}
              disabled={visible === '查看突发事件'}
            />
          }
        </Modal>
      </Layout >
    );
  }
}

export default connect(({ loading, global, emergency }) => ({ loading, global, modular: emergency }))(Form.create()(Index));